package com.cs.controller;


import com.cs.config.WechatConfig;
import com.cs.dto.UsersDto;
import com.cs.service.UsersService;
import com.cs.utils.UrlUtils;
import com.cs.utils.reids.RedisUtils;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author qf
 * @since 2021-08-04
 */
@Api("用户功能控制器")
@Slf4j
@RestController
@RequestMapping("/api/user")
public class UsersController {


    // 需要注入的三个对象
    @Autowired
    private UsersService usersService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired// redis工具类
    private WechatConfig wechatConfig;    // 微信设置


    // 1.获取code
    @ApiOperation(value = "微信登陆、注册", produces = "application/json", notes = "使用微信扫码进行快速登陆或注册。")
    @GetMapping("login/wechat")
    public void wechatLogin(HttpServletResponse response) {
        try {
            // 微信开放平台授权baseUrl
            String url = wechatConfig.getOpen_url() +
                    "?appid=" + wechatConfig.getAppid() +
                    "&redirect_uri=" + wechatConfig.getRedirect_uri() +
                    "&response_type=code" +
                    "&scope=" + wechatConfig.getScope() +
                    "&state=STATE#wechat_redirect";
            response.sendRedirect(url);
        } catch (IOException e) {
            log.error("唤起微信登录页面失败", e);
        }
    }

    // 2.获取access_token
    @GetMapping("wechat/callback")
    public void wechatCallback(String code, HttpServletResponse response) {
        log.info("微信给我们的code {}", code);

        // 1.获取access_token
        // 1.1 拼接访问微信的url
        String url = wechatConfig.getAccess_token_url() +
                "?appid=" + wechatConfig.getAppid() +
                "&secret=" + wechatConfig.getSecret() +
                "&code=" + code +
                "&grant_type=authorization_code";
        // 1.2 访问并获取返回值
        String resultJson = UrlUtils.loadURL(url);
        Map map = JSON.parseObject(resultJson, Map.class);

        // 1.3 获取accessToken 和openId
        String access_token = map.get("access_token").toString();
        String openid = map.get("openid").toString();
        log.info("获取的微信的access_token:{} openid:{}", access_token, openid);
        /**
         * 2.根据openid判断用户是不是第一次扫码，
         * 第一次获取用户信息，保存到数据库，给用户颁发token并跳转
         * 否则直接给用户颁发token并跳转
         */
        UsersDto usersDto = usersService.loginByWechat(access_token, openid);
        String token = usersDto.getToken();
        String userName = usersDto.getUserName();
        try {
            // 3.跳转
            String loginUrl = wechatConfig.getSuccess_url() + "?token=" + token + "&userInfo=" + URLEncoder.encode(userName, "UTF-8");
            response.sendRedirect(loginUrl);
        } catch (IOException e) {
            log.error("微信回调错误: {}" , e);
        }
    }
}

